package com.kx.game.center.servlet;

import com.kx.core.dawn.dbs.dao.DaoManager;
import com.kx.core.dawn.dbs.entity.GatewayEntity;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.local.response.LocalErrorResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 加载游戏服信息
 */
@WebServlet(urlPatterns = "/loadGateServerInfo", asyncSupported = true)
public class LoadGateServerServlet extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger(LoadGateServerServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            GSServices.loadManager.redisState();
            String timeMillis = System.currentTimeMillis() + "";
            //网关信息
            String gateId = request.getParameter("gateId");
            String gateIp = request.getParameter("gateIp");
            String gatePort = request.getParameter("gatePort");
            String gateCount = request.getParameter("gateCount");

//            String serverType = request.getParameter("serverType");
//            ServerEnum serverEnum;
//            if (serverType == null || serverType.equals("")) {
//                serverEnum = ServerEnum.indexOf(1);
//            } else
//                serverEnum = ServerEnum.indexOf(Integer.valueOf(serverType));
            //更新DB
            //网关信息
            if (gateId != null && !gateId.equals("")) {
                GatewayEntity gatewayEntity = DaoManager.gatewayDao.get(gateId);
                if (gatewayEntity == null) {
                    GSServices.gatewayManager.insert(gateId, 0, gateIp, gatePort, timeMillis);
                } else {
                    GSServices.gatewayManager.update(gatewayEntity, 0, gateIp, gatePort, timeMillis);
                }
            }

            GSServices.redisManager.getRedisTemplate().multi();
            GSServices.localManager.updateGatewayInfo(gateId, gateIp, gatePort);
            GSServices.localManager.updateGatewayLoad(gateId, Integer.valueOf(gateCount));
            GSServices.redisManager.getRedisTemplate().exec();
            GSServices.gameManager.printLog(request, logger, "gate服务器上线");
            GSServices.localManager.sendMessage(response, true, null, "");
        } catch (Exception e) {
            e.printStackTrace();
            GSServices.localManager.sendMessage(response, false, LocalErrorResponseCode.SYSTEM_ERROR, "");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
